package com.ruoyi.supply.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.supply.enums.DfStatusEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.supply.mapper.NewsMapper;
import com.ruoyi.supply.domain.News;

import javax.annotation.Nullable;

/**
 * 快讯Service业务层处理
 * 
 * @author Ryan
 * @date 2025-06-05
 */
@Service
@RequiredArgsConstructor
public class NewsService extends ServiceImpl<NewsMapper, News>
{
    private final NewsMapper newsMapper;

    /**
     * 查询快讯
     * 
     * @param id 快讯主键
     * @return 快讯
     */
    public News selectNewsById(Long id)
    {
        return newsMapper.selectNewsById(id);
    }

    /**
     * 查询快讯列表
     * 
     * @param news 快讯
     * @return 快讯
     */
    public List<News> selectNewsList(News news)
    {
        return newsMapper.selectNewsList(news);
    }

    /**
     * 新增快讯
     * 
     * @param news 快讯
     * @return 结果
     */
    public int insertNews(News news)
    {
        news.setStatus(DfStatusEnum.DF.getCode());
        news.setPushTime(new Date());
        news.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(news);
    }

    /**
     * 修改快讯
     * 
     * @param news 快讯
     * @return 结果
     */
    public int updateNews(News news)
    {
        news.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(news);
    }

    /**
     * 批量删除快讯
     * 
     * @param ids 需要删除的快讯主键
     * @return 结果
     */
    public int deleteNewsByIds(Long[] ids)
    {
        return newsMapper.deleteBatchIds(Arrays.asList(ids));
    }

    public List<News> getClientNews(@Nullable Integer size) {
        if(size == null){
            size = 100;
        }
        List<News> list = lambdaQuery().select(News::getTitle, News::getId,News::getCreateTime,News::getPushTime)
                .eq(News::getStatus, DfStatusEnum.DF.getCode())
                .orderByDesc(News::getPushTime)
                .orderByDesc(News::getCreateTime)
                .last("limit " + size)
                .list();
        return list;
    }

    public News getByClientId(Long id) {
        News news = getById(id);

        Assert.notNull(news,"数据异常，请刷新页面再操作！");
        Assert.notEquals(news.getStatus(),DfStatusEnum.DF.getDesc(),"当前数据已下架！");

        return news;
    }
}
